<?php

namespace App\Jobs;

use App\Http\GeneratePDF\newPDF;
use App\Http\Models\Billing;
use App\Http\Models\ProductInfo;
use App\Http\Models\RedisModel;
use App\Http\Models\RequestSuccess;
use App\Http\Services\AwsS3FilServer;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Mockery\Exception;

class ConfirmationRequestSendMail implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Create a new job instance.
     *
     * @return void
     */
    protected $redisModel;
    public function __construct(RedisModel $redisModel)
    {
        $this->redisModel = $redisModel;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle(): void
    {
        $companyInformation = $this->redisModel;
        $companyInformation = $companyInformation->companyInformation;
        $billingInformation = new Billing();
        $newPDF = new newPDF();
        foreach ($companyInformation as $companyInfor) {
            $unitPrice = config('businessVolume.UNIT_PRICE');
            $bankName = config('businessVolume.REQUEST_BANKNAME');
            $bankBranch = config('businessVolume.REQUEST_BANKBRANCH');
            $bankType = config('businessVolume.REQUEST_BANKTYPE');
            $bankCode = config('businessVolume.REQUEST_BANKNUMBER');
            $saleTax = config('businessVolume.SALE_TAX');
            $career = config('businessVolume.REQUEST_CAREER');
            $companyID = $companyInfor['id'];
            $userCompanyName = $companyInfor['user_company_name'];


            $billing_year_month = $companyInfor['billing_year_month'];
            $billing_date = $companyInfor['billing_date'];
            $requestDate = date('Y年m月d日', strtotime("$billing_year_month +2 month -1 day"));
            $sendMailDate = date('Y年m月d日', strtotime("$billing_date +1 day"));

//
//            $BeginDate=date('Y-m-01', strtotime(date("Y-m-d")));
//            $requestDate = date('Y年m月d日', strtotime("$BeginDate +1 month -1 day"));
            $sendMail = $companyInfor['billing_mail_addr'];
            $billId = $companyInfor['billId'];
            $sendMailName = $companyInfor['billing_add_name'];
            $billing_number = $companyInfor['billing_number'];
            $teamName = $companyInfor['team_name'];
//            $sendMailDate = date('Y年m月d日');
            $yearMonth = date('Y年m月', strtotime('-1 month'));
            $Price = $companyInfor['member_price'];
            $billingInfor = $billingInformation->getBillingInformation($companyID);
            $csvNumber = $billingInfor[0]->csv_number;
            $totalMoney = $billingInfor[0]->total_money;
            $noTaxPrice = ($unitPrice*$csvNumber) + $Price;
            $tax = (($unitPrice*$csvNumber) + $Price) * $saleTax;
            $usePrice = $unitPrice * $csvNumber;
            $data = [
                'companyName' => $userCompanyName,
                'unitMoney' => number_format($unitPrice),
                'totalMoney' => number_format($totalMoney),
                'usePrice' => number_format($usePrice),
                'sendMailName' => $sendMailName,
                'teamName' => $teamName,
                'csvNumber' => $csvNumber,
                'bankName' => $bankName,
                'bankBranch' => $bankBranch,
                'bankType' => $bankType,
                'bankCode' => $bankCode,
                'requestDate' => $requestDate,
                'sendMailDate' => $sendMailDate,
                'noTaxPrice' => number_format($noTaxPrice),
                'tax' => number_format($tax),
                'saleTax' => $saleTax,
                'yearMonth' => $yearMonth,
                'billing_number' => $billing_number,
                'career' => $career,
                'memberPrice' => number_format($Price)
            ];
            $subject = 'エコドラフト 請求書送付のご案内';
            $pdfReturn = $newPDF->requestBook($data);
            $attachments = [];
            $fileName = strstr($pdfReturn, 'ecodraft_invoice_');
            $attachments[$fileName] = $pdfReturn;
//        $attachments=["$userCompanyName"=>$pdfReturn];
            try {
                Mail::send("emails.RequestBookMails", $data, function ($message) use ($sendMail, $subject, $attachments) {
                    $message->from(config('mail.from')['address'], mb_encode_mimeheader(config('mail.from')['name']))
                        ->to($sendMail)
                        ->subject($subject);
                    foreach ($attachments as $alias => $attachment) {
                        $ext = pathinfo($attachment)['extension'];
                        $message->attach($attachment, ['as' => $alias]);
                    }
                });
                DB::table('billing')->where('id',"$billId")->update(array(
                    'csv_file_path' => '/' . strstr($pdfReturn, 'requestBook/'),
                    'status' => '請求確定',
                    'csv_file_name' => $fileName,
                ));
                $serverKbn = config('businessVolume.SERVER_KBN');
                if ($serverKbn !== "0") {
//                    if ($res) {
                    unlink($pdfReturn);
                    exec("rm -rf " . $pdfReturn);
//                    }
                }
            } catch (Exception $e) {
                \Log::info('Exception');
            }
        }
//        }
    }

    public function failed($exception = null)
    {
        \Log::info('error');
        $requestSuccess = new RequestSuccess();
        $requestSuccess->updateFlg(0);
    }
}
